package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.data.Result;
import com.dongdongshop.em.ConstantEnum;
import com.dongdongshop.pojo.*;
import com.dongdongshop.service.CartService;
import com.dongdongshop.service.TbOrderItemService;
import com.dongdongshop.service.TbOrderService;
import com.dongdongshop.util.CookieUtils;
import com.dongdongshop.util.IdWorker;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("cart")
public class CartController {


    @Reference
    private TbOrderService orderService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Reference
    private TbOrderItemService orderItemService;

    @Reference
    private CartService cartService;



    @RequestMapping("saveCookie")
    public String saveCookie(HttpServletRequest request, HttpServletResponse response, Long itemId, Integer num){
        // 获取登录用户
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();

        // 用户没有登录的情况下 添加购物车
        // 先从cookie 查询原来的 购物车
        List<Cart> cartList = getCookie(request,response);
        // 组装购物车
        cartList = cartService.saveCart(cartList,itemId,num);

        if (user == null){
            // 保存 cookie
            CookieUtils.setCookie(request,response,"cartList",JSONObject.toJSONString(cartList),true);
        }else {
            cartService.saveCartListRedis(cartList,user.getUsername());
        }

        return "cart";
    }


    @RequestMapping("getCookie")
    @ResponseBody
    public List<Cart> getCookie(HttpServletRequest request,HttpServletResponse response){
        // 获取登录用户
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        // 判断用户是否登录
        String cartListStr = CookieUtils.getCookieValue(request, "cartList", true);
        if (StringUtils.isBlank(cartListStr)){
            cartListStr = "[]";
        }
        // 将json格式的字符串  通过fastJson 转为对象
        // 从cookie中获取购物车
        List<Cart> cartCookieList = JSONObject.parseArray(cartListStr, Cart.class);
        if (user == null){ // 未登录
            return cartCookieList;
        }else {
            // 从redis 中获取购物车
            List<Cart> cartRedisList = cartService.getCartListFormRedis(user.getUsername());
            // cookie 中有购物信息的话才需要合并
            if (cartCookieList.size() > 0){
                // 合并 购物车
                List<Cart> merAgeCartList = cartService.merAgeCartList(cartRedisList,cartCookieList);

                // 将合并好的购物车 从新保存进redis
                cartService.saveCartListRedis(merAgeCartList, user.getUsername());

                // 删除 cookie 中的购物车
                CookieUtils.deleteCookie(request,response,"cartList");
                return merAgeCartList;
            }else { // cookie 中没有数据直接返回 redis中的 购物信息
                return cartRedisList;
            }
        }
    }

//    @RequestMapping("saveCookie")
//    @ResponseBody
//    public String saveCookie(HttpServletRequest request, HttpServletResponse response){
//        CookieUtils.setCookie(response,"testCookie","test",true);
//        return "ok";
//    }
//
//    @RequestMapping("getCookie")
//    @ResponseBody
//    public String getCookie(HttpServletRequest request){
//        String cookieValue = CookieUtils.getCookieValue(request, "testCookie", "test");
//        return cookieValue;
//    }

    // 生成订单
    @RequestMapping("addByInfo")
    @ResponseBody
    public Result addByInfo(Long id){
        try {
            TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
            TbAddress tbAddress = orderService.getAddressById(id);
            IdWorker workerId = new IdWorker();
            long idOrder = workerId.nextId();
            Map<String,Object> map = new HashMap<>();
            String title = null;
            List<Cart> cartList = (List<Cart>) redisTemplate.boundHashOps("cartList").get(user.getUsername());
            for (Cart cart : cartList) {
                IdWorker idWorker = new IdWorker();
                long orderId = idWorker.nextId();
                TbOrder tbOrder = new TbOrder(); //新建订单对象
                tbOrder.setOrderId(orderId); //订单Id
                tbOrder.setUserId(tbAddress.getUserId());//用户名
                tbOrder.setPaymentType("1");//支付类型
                tbOrder.setStatus("1");// 状态:未付款
                tbOrder.setCreateTime(new Date()); //订单创建日期
                tbOrder.setUpdateTime(new Date()); //订单更新日期
                tbOrder.setReceiverAreaName(tbAddress.getAddress());//地址
                tbOrder.setReceiverMobile(tbAddress.getMobile());//手机号
                tbOrder.setReceiver(tbAddress.getContact());//收货人
                tbOrder.setSourceType("2");//订单来源
                tbOrder.setSellerId(user.getUsername());//商家id

                IdWorker idWorker1 = new IdWorker();
                long orderId1 = idWorker1.nextId();
                tbOrder.setOutTradeNo(Long.toString(orderId1));// 订单号

                //循环购物车明细
                double menoy = 0;
                for (TbOrderItem orderItem : cart.getOrderItemList()) {
                    orderItem.setId(idWorker.nextId());
                    orderItem.setOrderId(orderId); //订单的id

                    orderItem.setOutTradeNo(Long.toString(orderId1)); //订单号

                    orderItem.setSellerId(cart.getSellerId());
                    menoy += orderItem.getTotalFee().doubleValue();//金额累加
                    orderItemService.insert(orderItem);
                    title = orderItem.getTitle();
                }
                map.put("menoy",menoy);
                String str=idOrder+"";
                map.put("orderId",idOrder);
                map.put("title",title);
                map.put("WIDout_trade_no",Long.toString(orderId1));

                tbOrder.setPayment(new BigDecimal(menoy));
                orderService.insert(tbOrder);
            }

            redisTemplate.boundHashOps("cartList").delete(user.getUsername());

            return Result.build(ConstantEnum.SUCCESS).setResult(map);
        }catch (Exception e){
            e.printStackTrace();
            return Result.build(ConstantEnum.ERROR);
        }
    }

    // 添加支付流水号
    @RequestMapping("getTradeNoInfo")
    @ResponseBody
    public Result getTradeNoInfo(TbOrder tbOrder){
        orderService.updateBYOTN(tbOrder.getTradeNo(),tbOrder.getOutTradeNo());
        // 详情表
        orderItemService.insertBYOTN(tbOrder.getTradeNo(),tbOrder.getOutTradeNo());
        return Result.build(ConstantEnum.SUCCESS);
    }





//    //跳转支付页面
//    @RequestMapping("toPay")
//    public String toPay(String orderId, Double money, Model model){
//        model.addAttribute("orderId","订单提交成功，请您及时付款！订单号:"+orderId);
//        model.addAttribute("money","￥"+money);
//        return "pay";
//    }

}
